#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/11/15 11:47
# file: redis.py
# author: lotus163
from fastapi import FastAPI
from loguru import logger

from backend.config.setting import settings
from backend.core.redis import MyRedis


async def register_redis(app: FastAPI):
    redis: MyRedis = await init_redis_pool()  # redis
    app.state.redis = redis
    await redis.loading_config_cache()  # 将config载入redis
    await redis.loading_dict_cache()  # 将dict载入redis


# 参考: https://github.com/grillazz/fastapi-redis/tree/main/app
async def init_redis_pool() -> MyRedis:
    """ 连接redis """
    result = await MyRedis.from_url(url=settings.REDIS_URL, encoding=settings.GLOBAL_ENCODING, decode_responses=True)
    logger.info("初始化redis成功")
    return result
